$(function() {
	mui.init();
	mui.previewImage();
	mui.ready(function() {
		var userid = localStorage.getItem('userid');
		var token = localStorage.getItem('token');
		var caseid = localStorage.getItem('caseid');
		var postData = {
			caseid: caseid,
			userid: userid,
			token: token,
		};
		// mui.alert(caseid);
		var type = {
			"1": {
				"name": "半月",
				"class": "half"
			},
			"2": {
				"name": "季度",
				"class": "quarter",
			},
			"3": {
				"name": "半年",
				"class": "half_year"
			},
			"4": {
				"name": "年度",
				"class": "year"
			}
		};
		// 图片追尾的数字
		// var num = 0;
		var numArr = [0, 1, 2, 3];

		//清缓存
		localStorage.removeItem('isAC'); //是否外接电源		
		localStorage.removeItem('d');
		localStorage.removeItem('MAC');
		localStorage.removeItem('endtime'); //结束时间	
		localStorage.removeItem('starttime'); //开始时间
		localStorage.removeItem('signStaut');
		localStorage.removeItem('loc_starttime'); //
		localStorage.removeItem('loc_endtime'); //
		// 签到需要的参数	
		var bluetoothid = localStorage.getItem('bluetoothid');
		var loc_starttime = localStorage.getItem(caseid + 'loc_starttime');
		var loc_endtime = localStorage.getItem(caseid + 'loc_endtime');

		init(postData);
		getStoragePhoto();
		// 初始化请求
		function init(postData) {
			mui.showLoading("正在加载..", ".mui-content");
			$.ajax(domain + "/dtwbgl/wbprocessdesc.h5", {
				// data: JSON.stringify(postData),
				data: postData,
				dataType: 'json', //服务器返回json格式数据
				type: 'post', //HTTP请求类型
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
				},
				async: true, //true异步加载
				success: function(data) {
					console.log(JSON.stringify(data));
					if (data.code == 2001) {
						var postList = data.data;
						// 工单对应的ip
						var ctr_user = postList.ctr_user;
						var ctr_wbr = postList.ctr_wbr;
						var kind = postList.kind;
						localStorage.setItem('ctr_user', ctr_user);
						localStorage.setItem('ctr_wbr', ctr_wbr);
						localStorage.setItem('kind', kind);
						var typeName = type[postList.jhtype].name;
						bluetoothid = postList.bluetoothid;
						console.log(bluetoothid);
						$(".txtbox h2:nth-child(1) span").html(postList.caseid);
						$(".txtbox h2:nth-child(1) b u").html(typeName);
						$(".txtbox h2:nth-child(2) span").html(postList.xdtime);
						$(".txtbox h2:nth-child(3) span").html(postList.jdtime);
						$(".repair-type-box.monbox p:nth-child(1) span").html(postList.dttype);
						$(".repair-type-box.monbox p:nth-child(2) span").html(postList.dtdz);
						$(".repair-type-box.monbox p:nth-child(3) span").html(postList.dtcode);
						$('.submitAll').click(function() {
							submitAll(postList);
						});
						// 配件/维保项
						mui('.padbox .mui-table .redirect').on('tap', 'a', function() {
							let url = $(this).data('url');
							redirect(postList, url);
						});

						$(".qian").click(function() {
							sign(postList);
						})

						// 没有蓝牙签到modal
						$(".Agree").click(function() {
							sign_action(postList);
						});
						mui.hideLoading();
					} else if (data.code == 2002) {
						mui.toast(data.msg);
						mui.openWindow({
							url: '../../login.html',
							id: '../../login.html'
						})
					} else {
						mui.toast(data.msg);
						mui.openWindow({
							url: '../../404.html',
							id: '../../404.html'
						})
					}
				},
				error: function(xhr, type, errorThrown) {
					//异常处理；
					console.log(type);
					mui.alert(type);
					mui.openWindow({
						url: '../../login.html',
						id: 'login.html'
					})
				}
			});
		}

		mui('#btncameara').on('tap', 'a', function() {
			mui('#picture').popover('toggle'); // 先关闭弹出层
			// 调用相机
			// console.log(1);
			startCamera('startcamera');
			return false
		});
		// 删除图片
		mui('.scene').on('tap', 'i', function() {
			//console.log(this);
			//得到这个button的直接父亲,然后从DOM中移除
			numArr.unshift($(this).parent().find('img').data('index'));

			$(this).parent().remove();
			setStoragePhoto();
			if ($("#photo li").length < 4) {
				$('.upload_img').show();
			}

			// savePicByLocolStorage(); // 移除后重新获取照片列表
		});
		// 调用相机
		function startCamera(param) {
			//创建event的对象实例。  
			// console.log(4);
			var event = document.createEvent('MouseEvents');
			// 3个参数：事件类型，是否冒泡，是否阻止浏览器的默认行为  
			event.initEvent("click", false, false);
			/*属性，随便自己定义*/
			//触发自定义事件oneating  
			var f = document.getElementById(param)
			f.dispatchEvent(event);
			$('#startcamera').off('change').on('change', function() {
				readURL(this);
				// console.log(5);
			});
		}
		// 把照片读取成base64格式
		function readURL(input) {															
			var uploadUrl = 'http://' + localStorage.getItem('middleserver') + ':' + localStorage.getItem(
				'uploadport') + '/';
			var downloadUrl = 'http://' + localStorage.getItem('middleserver') + ':' + localStorage.getItem(
				'downloadport') + '/';
				
			// 			if (checkPic() > 3) {
			// 				mui.toast("只能选择4张照片");
			// 				return;
			// 			};
			if (input.files && input.files[0]) {
				mui.showLoading("正在加载..", ".mui-content");
				const
					reader = new FileReader();
				reader.readAsDataURL(input.files[0]);
				/*reader.onload = (e) => {
					$('#imgShow').attr('src', e.target.result);
				};*/
				reader.onload = function(e) {
					
					var base64info = e.target.result;
					// base64 										
					var blob = dataURItoBlob(base64info);
					var fd = new FormData();
					var num = numArr.shift();
					// var num = Math.round(new Date() / 1000) + Math.floor((Math.random() * 100) + 1);
					var img = 'sig_' + localStorage.getItem('caseid').trim() + '_' + num + '.jpg';
					console.log(num)
					fd.append("f", blob, img);
					$.ajax({
						url: uploadUrl + 'upload',
						type: 'POST',
						data: fd,
						// dataType: 'JSON',
						cache: false,
						processData: false,
						contentType: false,
						traditional: true,
						success: function(res) {
							//隐藏加载框
							mui.hideLoading(function() { //隐藏后的回调函数  
							});
							if (res == 'ok') {
								let src = downloadUrl + img;
								//<i class="mui-icon mui-icon-closeempty"></i>
								let li = '<li> <i class="mui-icon mui-icon-closeempty"></i><span><img src="' + base64info +'" data-preview-src="' + src + '" data-preview-group="1" data-fn="' + img + '" data-index="' + num +'" height="70px" ></span></li>';
								$('#photo').append(li);
								$("input[name=files]").val('');
								mui.toast('上传成功');								
								// delePoto()
								// local存储
								setStoragePhoto();

								if (!numArr.length) {
									mui.toast('最多传4张照片');
									$('.upload_img').hide();
								}
							} else {
								mui.toast('上传失败');
								mui.hideLoading(function() { //隐藏后的回调函数  
								});
							}
						}
					});
				}
			}
		}
		// 图片删除
		// function delePoto(){
		// 	// 删除图片
		// 	mui('.scene').on('tap', 'i', function() {
		// 		//console.log(this);
		// 		//得到这个button的直接父亲,然后从DOM中移除
		// 		$(this).parent().remove();
		// 		setStoragePhoto(); // 移除后重新获取照片列表

		// 	});
		// 	num--;
		// }
		// 图片存储
		function setStoragePhoto() {
			var piclist = [];
			$("#photo li").each(function(i, e) {
				var src = $(e).find('img').data('preview-src');
				var fn = $(e).find('img').data('fn');
				var index = $(e).find('img').data('index');
				var item = {
					src: src,
					fn: fn,
					index: index
				}
				piclist.push(item);
			});
			localStorage.setItem('photo_' + localStorage.getItem('caseid'), JSON.stringify(piclist));
		}
		// 图片存储
		function getStoragePhoto() {
			var piclist = localStorage.getItem('photo_' + localStorage.getItem('caseid'));
			piclist = JSON.parse(piclist);

			var lis = '';
			if (!piclist) {
				return;
			}
			piclist.forEach(function(e, i) {
					// console.log(e);
				numArr.splice(numArr.indexOf(e.index), 1);
				lis += '<li><i class="mui-icon mui-icon-closeempty"></i><span><img src="' + e.src + '" data-preview-src="' + e.src +'" data-preview-group="1" data-fn="' + e.fn + '" data-index="' + e.index + '" height="70px" ></span></li>';
				num = (i + 1);
			});
			$('#photo').append(lis);
			if ($('#photo li').length >= 4) {
				$('.upload_img').hide();
			}
		}
		// 总提交
		function submitAll(data) {
			// wblist	
			mui.showLoading("正在加载..", ".warn-list");
			var wblist = localStorage.getItem(data.caseid + '_wblist');
			wblist = JSON.parse(wblist);
			if (!wblist) {
				//隐藏加载框
				mui.hideLoading(function() { //隐藏后的回调函数  
				});
				mui.toast('请先填维保项');
				return false;

			}
			var wbxlist = new Array();
			wblist.forEach(function(e, i) {
				e.item.forEach(function(v, k) {
					var item = {
						bz: v.reason,
						ifok: v.ifok,
						id: v.subid
					}
					wbxlist.push(item);
				});
			});
			// pic
			var piclist = new Array();
			if ($("#photo li").length <= 0) {
				//隐藏加载框
				mui.hideLoading(function() { //隐藏后的回调函数  
				});
				mui.toast('请先上传图片');
				return false;

			}
			$("#photo li").each(function(i, e) {
				var src = $(e).find('img').data('preview-src');
				var fn = $(e).find('img').data('fn');
				var item = {
					address: src,
					fn: fn
				}
				piclist.push(item);
			});
			// 签退判断

			var wb_in = localStorage.getItem(data.caseid + '_sign_in');
			console.log(wb_in);
			if (wb_in == 0) {
				mui.toast('请签退');
				mui.hideLoading(function() { //隐藏后的回调函数  
				});
				return false;
			}
			// pflist			
			var pjlist = localStorage.getItem(data.caseid + '_pjlist');
			pjlist = JSON.parse(pjlist);
			var btdata = submitbule();
			console.log(btdata);
			// 经纬度
			//var lats=$('body').attr("data-lat");					
			//var lags=$('body').attr("data-lng");	

			// 2019-01-08
			var lats = localStorage.getItem('wbapplat');
			var lags = localStorage.getItem('wbapplng');

			var postDatas = {
				userid: userid,
				token: token,
				kind: data.kind,
				caseid: caseid,
				actionid: data.actionid,
				long: lags,
				lat: lats,
				time: getNowFormatDate(),
				pz: data.pz,
				bz2: data.bz2,
				change: "",
				wbxlist: wbxlist,
				piclist: piclist,
				gzlx2: "",
				gzyy2: "",
				bluetooth: btdata,
				base: "",
				pj: pjlist
			}
			console.log(postDatas);

			$.ajax(domain + "/dtwbgl/wbwbtj.h5", {
				data: JSON.stringify(postDatas),
				dataType: 'json', //服务器返回json格式数据
				type: 'post', //HTTP请求类型
				headers: {
					'Content-Type': 'application/json'
				},
				async: true, //true异步加载
				success: function(data) {

					if (data.code == 3001) {
						mui.toast('提交成功');
						// 						mui.openWindow({
						// 							url: 'year-warn.html#processing',
						// 							id: 'year-warn.html'
						// 						})
						// window.location.replace('year-warn.html#processing');
						window.history.go(-1);
					} else {
						//隐藏加载框
						mui.hideLoading(function() { //隐藏后的回调函数  
						});
						mui.toast('提交失败');
					}
					console.log(data);
				},

			});
		}
		// 没有蓝牙的签到		
		function sign(postList) {
			var sign_in = localStorage.getItem(postList.caseid + "_sign_in");
			// mui.alert(sign_in);
			var now = getNowFormatDate();
			var check = function() {
				var wblist = localStorage.getItem(postList.caseid + "_wblist");
				var flag = true;
				if (!wblist) {
					mui.toast('维保项内容没有填全');
					return false;
				}
				var imges = $('#photo li');
				if (imges.length == 0) {
					mui.toast('请先上传图片');
					return false;
				}
				wblist = JSON.parse(wblist);
				wblist.forEach(function(value, index) {
					value.item.forEach(function(v, i) {
						if (v.ifok == "") {
							flag = false;
							return false;
						}
					});
				});
				if (flag === false) {
					mui.toast('维保项内容没有填全');
					return false;
				}
				return true;
			}
			if (postList.bluetoothid != '' && postList.bluetoothid != null) {
				switch (sign_in) {
					case "0":
						if (!check()) {
							return false;
						}
						var ahref = 'dt:req=bt_end;start=' + localStorage.getItem(caseid + 'loc_starttime') + ';sn=' + bluetoothid;
						$(this).find('a').attr('href', ahref);
						window.location.href = ahref;
						// 	$(this).find('a').attr('href', 'javascript:;');
						loc_endtime = getNowFormatDate(); //结束时间
						localStorage.setItem('loc_endtime', loc_endtime);
						break;
					case "1":
						mui.toast("已签退");
						break;
					default:
						var ahref = 'dt:req=bt_start;sn=' + bluetoothid;
						$(this).find('a').attr('href', ahref);
						window.location.href = ahref;
				}
			} else {
				switch (sign_in) {
					case "0":
						if (!check()) {
							return false;
						}
						$(".tui").find('.time').text(now);
						$(".tui").show();
						break;
					case "1":
						mui.toast("已签退");
						break;
					default:
						$(".dao").find('.time').text(now);
						$(".dao").show();
				}
			}
		}
		// 有蓝牙的签到 值的存储

		// 没有蓝牙的签到modal
		function sign_action(postList) {
			var sign_in = localStorage.getItem(postList.caseid + "_sign_in");
			if (sign_in == 0) {
				localStorage.setItem(postList.caseid + "_sign_in", "1");
				mui.toast("签退成功")
			} else if (sign_in == null) {
				localStorage.setItem(postList.caseid + "_sign_in", "0");
				mui.toast("签到成功")
			}
			setTimeout(function() {
				$(".dao").hide();
				$(".tui").hide();
			}, 1000);
		}

		// 点击跳转
		function redirect(postList, url) {
			var sign_in = localStorage.getItem(postList.caseid + "_sign_in");
			if (!sign_in) {
				mui.toast("请签到！");
				return false;
			}
			//跳转配置页
			mui.openWindow({
				url: url,
				id: url
			});
		}
		//bluetooth 上传   00000
		function submitbule() {
			// MAC,开始登记时间,防拆计数,是否外接电源，结束登记时间，持续秒数
			var mac = localStorage.getItem('MAC');
			var isAC = localStorage.getItem('isAC');
			var d = localStorage.getItem('d');
			var start = loc_starttime;
			var end = loc_endtime;
			var cxtime = timeCal(start, end);
			return mac + ',' + start + ',' + d + ',' + isAC + ',' + end + ',' + cxtime;
		}
		//时间计算
		function timeCal(time1, time2) {
			var date1 = new Date(time1)
			var date2 = new Date(time2)
			var s1 = date1.getTime(),
				s2 = date2.getTime();
			var total = (s2 - s1) / 1000;
			var miao = parseInt(total);
			return miao;
		}
		//获取当前时间转换格式
		function format(Date) {
			var Y = Date.getFullYear();
			var M = Date.getMonth() + 1;
			M = M < 10 ? '0' + M : M; // 不够两位补充0
			var D = Date.getDate();
			D = D < 10 ? '0' + D : D;
			var H = Date.getHours();
			H = H < 10 ? '0' + H : H;
			var Mi = Date.getMinutes();
			Mi = Mi < 10 ? '0' + Mi : Mi;
			var S = Date.getSeconds();
			S = S < 10 ? '0' + S : S;
			return Y + '-' + M + '-' + D + ' ' + H + ':' + Mi + ':' + S;
		}

	});
});
//h5 原生交互传值函数
function btOK(req, sn, mac, isAC, d, time) {
	//保留下各个参数，提交时候用
	//此函数所有参数都是字符串类型
	var caseid = localStorage.getItem('caseid');
	if (req == 'bt_end') {
		localStorage.setItem('isAC', isAC);
		localStorage.setItem('d', d); //防拆计数			
		localStorage.setItem('MAC', mac);
		localStorage.setItem('endtime', time);
		if (time != '') {
			loc_endtime = time;
			localStorage.setItem(caseid + 'loc_endtime', loc_endtime);
			localStorage.setItem(caseid + "_sign_in", 1);
			console.log("bt_end <>set后get" + localStorage.getItem(caseid + "_sign_in"));
		} else {
			loc_endtime = localStorage.getItem('loc_endtime');
			localStorage.setItem(caseid + 'loc_endtime', loc_endtime);
			localStorage.setItem(caseid + "_sign_in", 1);
			console.log("bt_end set后get" + localStorage.getItem(caseid + "_sign_in"));
		}
	} else if (req == 'bt_start') {
		localStorage.setItem('starttime', time);
		if (time != '') {
			loc_starttime = time;
			localStorage.setItem(caseid + 'loc_starttime', loc_starttime);
			localStorage.setItem(caseid + "_sign_in", 0);
		} else {
			loc_starttime = getNowFormatDate();
			localStorage.setItem(caseid + 'loc_starttime', loc_starttime);
			localStorage.setItem(caseid + "_sign_in", 0);
		}

	}

}
